package com.geostar.constructionland.attachment.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wuyongzhi
 * @since 2020-08-04
 **/
@Slf4j
@Component
public class FTPUtil {

    /**
     * 该目录不存在
     */
    public static final String DIR_NOT_EXIST = "该目录不存在";

    /**
     * "该目录下没有文件
     */
    public static final String DIR_CONTAINS_NO_FILE = "该目录下没有文件";

    /**
     * 本地字符编码
     **/
    private static String localCharset = "GBK";

    /**
     * FTP协议里面，规定文件名编码为iso-8859-1
     **/
    private static String serverCharset = "ISO-8859-1";

    /**
     * UTF-8字符编码
     **/
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * OPTS UTF8字符串常量
     **/
    private static final String OPTS_UTF8 = "OPTS UTF8";

    /**
     * 设置缓冲区大小4M
     **/
    private static final int BUFFER_SIZE = 1024 * 1024 * 4;

    /**
     * 获取文件大小
     * @param ftpAddress
     * @param ftpPort
     * @param ftpUsername
     * @param ftpPassword
     * @param ftpPath
     * @param ftpFileName
     * @return
     */
    public Long getSize(String ftpAddress, int ftpPort, String ftpUsername, String ftpPassword, String ftpPath, String ftpFileName) {
        Long fileSize = null;
        // 登录
        FTPClient ftpClient = login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        if (ftpClient != null) {
            String remotePath = changeEncoding(ftpClient, ftpPath);
            if(! checkFileInFtp(ftpClient, remotePath, ftpFileName)) {
                return null;
            }
            try {
                String ftpName = new String(ftpFileName.getBytes(localCharset), serverCharset);
                FTPFile[] fs = ftpClient.listFiles(ftpName);
                fileSize = fs[0].getSize();
            } catch (Exception e) {
                log.error("##########FTP获取文件大小失败！", e);
                return null;
            } finally {
                closeConnect(ftpClient);
            }
        }
        return fileSize;
    }

    /**
     *  下载指定文件到本地
     * @param ftpAddress FTP IP地址
     * @param ftpPort FTP端口号
     * @param ftpUsername FTP用户名
     * @param ftpPassword FTP密码
     * @param ftpPath FTP路径
     * @param ftpFileName 指定下载的文件名称
     * @param savePath 保存路径
     * @return
     */
    public boolean downloadFile(String ftpAddress, int ftpPort, String ftpUsername, String ftpPassword, String ftpPath, String ftpFileName, String savePath) {
        // 登录
        FTPClient ftpClient = login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        if (ftpClient != null) {
            String remotePath = changeEncoding(ftpClient, ftpPath);
            if(! checkFileInFtp(ftpClient, remotePath, ftpFileName)) {
                return Boolean.FALSE;
            }
            ftpClient.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据
            File fileDir = new File(savePath);
            if(! fileDir.exists()) {
                fileDir.mkdirs();
            }
            File file = new File(savePath + File.separator + ftpFileName);
            OutputStream os = null;
            try {
                String ftpName = new String(ftpFileName.getBytes(localCharset), serverCharset);
                if(file.exists()) {
                    FTPFile[] fs = ftpClient.listFiles(ftpName);
                    if(fs[0].getSize() == file.length()) {  // 若已经存在，不再下载
                        return Boolean.TRUE;
                    }
                }
                os = new FileOutputStream(file);
                ftpClient.retrieveFile(ftpName, os);
            } catch (Exception e) {
                log.error("##########FTP下载文件失败", e);
                return Boolean.FALSE;
            } finally {
                closeConnect(ftpClient);
                try {
                    if(os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 下载指定目录下所有文件到本地
     *
     * @param ftpAddress FTP IP地址
     * @param ftpPort FTP端口号
     * @param ftpUsername FTP用户名
     * @param ftpPassword FTP密码
     * @param ftpPath  FTP服务器上的路径
     * @param savePath 保存文件到本地的路径，例如：D:/test
     * @return 成功返回true，否则返回false
     */
    public boolean downloadFiles(String ftpAddress, int ftpPort, String ftpUsername, String ftpPassword, String ftpPath, String savePath) {
        // 登录
        FTPClient ftpClient = login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        if (ftpClient != null) {
            OutputStream os = null;
            try {
                String path = changeEncoding(ftpClient, ftpPath);
                // 判断是否存在该目录
                if(! checkPathInFtp(ftpClient, path)) {
                    return Boolean.FALSE;
                }
                ftpClient.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据
                String[] fs = ftpClient.listNames();
                // 创建文件夹
                String fileDirName = savePath + File.separator + ftpPath;
                File fileDirs = new File(fileDirName);
                if(! fileDirs.exists()) {
                    fileDirs.mkdirs();
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    File file = new File(fileDirName + File.separator + ftpName);
                    os = new FileOutputStream(file);
                    ftpClient.retrieveFile(ff, os);
                }
                return Boolean.TRUE;
            } catch (IOException e) {
                log.error("##########FTP下载文件失败", e);
            } finally {
                closeConnect(ftpClient);
                try {
                    if(os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Boolean.FALSE;
    }

    /**
     * 下载指定目录下所有文件到本地
     *
     * @param ftpAddress FTP IP地址
     * @param ftpPort FTP端口号
     * @param ftpUsername FTP用户名
     * @param ftpPassword FTP密码
     * @param ftpPath  FTP服务器上的相对路径，例如：test/123
     * @param savePath 保存文件到本地的路径，例如：D:/test
     * @return 成功返回true，否则返回false
     */
    public Map<String, Object> downLoadFiles(String ftpAddress, int ftpPort, String ftpUsername, String ftpPassword, String ftpPath, String savePath) {
        // 登录
        FTPClient ftpClient = login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        Map<String, Object> resultMap = new HashMap<>();
        if (ftpClient != null) {
            OutputStream os = null;
            try {
                String path = changeEncoding(ftpClient, ftpPath);
                // 判断是否存在该目录
                if(! checkPathInFtp(ftpClient, path)) {
                    resultMap.put("result", false);
                    return resultMap;
                }
                ftpClient.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据
                String[] fs = ftpClient.listNames();
                List<String> fileNameList = new ArrayList<>();
                // 创建文件夹
                String fileDirName = savePath + File.separator + ftpPath;
                File fileDirs = new File(fileDirName);
                if(! fileDirs.exists()) {
                    fileDirs.mkdirs();
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    File file = new File(fileDirName + File.separator + ftpName);
                    // 存储文件名导入时使用
                    fileNameList.add(fileDirName + File.separator + ftpName);
                    os = new FileOutputStream(file);
                    ftpClient.retrieveFile(ff, os);
                }
                resultMap.put("fileNameList", fileNameList);
                resultMap.put("result", true);
                return resultMap;
            } catch (IOException e) {
                log.error("##########FTP下载文件失败", e);
            } finally {
                closeConnect(ftpClient);
                try {
                    if(os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        resultMap.put("result", false);
        return resultMap;
    }

    /**
     * 检查指定目录下是否含有指定文件
     *
     * @param ftpAddress FTP IP地址
     * @param ftpPort FTP端口号
     * @param ftpUsername FTP用户名
     * @param ftpPassword FTP密码
     * @param ftpPath  FTP服务器文件相对路径，例如：test/123
     * @param fileName 要下载的文件名，例如：test.txt
     * @return 成功返回true，否则返回false
     */
    public boolean checkFileInFtp(String ftpAddress, int ftpPort, String ftpUsername, String ftpPassword, String ftpPath, String fileName) {
        // 登录
        FTPClient ftpClient = login(ftpAddress, ftpPort, ftpUsername, ftpPassword);
        if (ftpClient != null) {
            try {
                String path = changeEncoding(ftpClient, ftpPath);
                // 判断是否存在该目录
                if (! ftpClient.changeWorkingDirectory(path)) {
                    log.error("##########FTP检查指定目录下是否含有指定文件：{}{}", ftpPath + DIR_NOT_EXIST);
                    return Boolean.FALSE;
                }
                ftpClient.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据
                String[] fs = ftpClient.listNames();
                // 判断该目录下是否有文件
                if (fs == null || fs.length == 0) {
                    log.error("##########FTP检查指定目录下是否含有指定文件：{}{}", ftpPath + DIR_CONTAINS_NO_FILE);
                    return Boolean.FALSE;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        return Boolean.TRUE;
                    }
                }
            } catch (IOException e) {
                log.error("##########FTP检查指定目录下是否含有指定文件：请求出错", e);
            } finally {
                closeConnect(ftpClient);
            }
        }
        return Boolean.FALSE;
    }

    /**
     * 检查指定目录下是否含有指定文件
     *
     * @param ftpClient FTP对象
     * @param ftpPath  FTP服务器文件相对路径，例如：test/123
     * @param fileName 要下载的文件名，例如：test.txt
     * @return 成功返回true，否则返回false
     */
    private boolean checkFileInFtp(FTPClient ftpClient, String ftpPath, String fileName) {
        if (ftpClient != null) {
            try {
                String path = changeEncoding(ftpClient, ftpPath);
                // 判断是否存在该目录
                if (! ftpClient.changeWorkingDirectory(path)) {
                    log.error("##########FTP检查指定目录下是否含有指定文件：{}{}", ftpPath + DIR_NOT_EXIST);
                    return Boolean.FALSE;
                }
                ftpClient.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据
                String[] fs = ftpClient.listNames();
                // 判断该目录下是否有文件
                if (fs == null || fs.length == 0) {
                    log.error("##########FTP检查指定目录下是否含有指定文件：{}{}", ftpPath + DIR_CONTAINS_NO_FILE);
                    return Boolean.FALSE;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        return Boolean.TRUE;
                    }
                }
            } catch (IOException e) {
                log.error("##########FTP检查指定目录下是否含有指定文件：请求出错", e);
            }
        }
        return Boolean.FALSE;
    }

    /**
     * 检查指定目录是否存在
     *
     * @param ftpClient FTP对象
     * @param ftpPath  FTP服务器文件路径
     * @return 成功返回true，否则返回false
     */
    private boolean checkPathInFtp(FTPClient ftpClient, String ftpPath) {
        if (ftpClient == null) {
            return Boolean.FALSE;
        } else {
            try {
                String path = changeEncoding(ftpClient, ftpPath);
                // 判断是否存在该目录
                if (! ftpClient.changeWorkingDirectory(path)) {
                    log.error("##########FTP检查指定目录下是否含有指定文件：{}{}", ftpPath + DIR_NOT_EXIST);
                    return Boolean.FALSE;
                }
                ftpClient.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据
                String[] fs = ftpClient.listNames();
                // 判断该目录下是否有文件
                if (fs == null || fs.length == 0) {
                    log.error("##########FTP检查指定目录下是否含有指定文件：{}{}", ftpPath + DIR_CONTAINS_NO_FILE);
                    return Boolean.FALSE;
                }
            } catch (IOException e) {
                log.error("##########FTP检查指定目录下是否含有指定文件：请求出错", e);
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 连接FTP服务器
     *
     * @param address  地址，如：127.0.0.1
     * @param port     端口，如：21
     * @param username 用户名，如：root
     * @param password 密码，如：root
     */
    private FTPClient login(String address, int port, String username, String password) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(address, port);
            ftpClient.login(username, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //限制缓冲区大小
            ftpClient.setBufferSize(BUFFER_SIZE);
            int reply = ftpClient.getReplyCode();
            if (! FTPReply.isPositiveCompletion(reply)) {
                closeConnect(ftpClient);
                log.error("##########FTP服务器连接失败");
            }
        } catch (Exception e) {
            log.error("##########FTP登录失败", e);
        }
        return ftpClient;
    }

    /**
     * FTP服务器路径编码转换
     *
     * @param ftpClient FTP对象
     * @param ftpPath FTP服务器路径
     * @return String
     */
    private static String changeEncoding(FTPClient ftpClient, String ftpPath) {
        String directory = null;
        try {
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                localCharset = CHARSET_UTF8;
            }
            directory = new String(ftpPath.getBytes(localCharset), serverCharset);
        } catch (Exception e) {
            log.error("##########FTP路径编码转换失败", e);
        }
        return directory;
    }

    /**
     * 关闭FTP连接
     * @param ftpClient FTP对象
     */
    private void closeConnect(FTPClient ftpClient) {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                log.error("##########关闭FTP连接失败", e);
            }
        }
    }

}
